# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 13:49
# @Author  : CHNJX
# @File    : device.py
# @Desc    :

# api/routes/device.py
from flask import Blueprint, request
from app.model import Device
from app.utils.response_handler import response_with_handler, success_response, error_response

device_bp = Blueprint('device', __name__)


@device_bp.route('/', methods=['GET'])
@response_with_handler
def get_devices():
    """获取所有设备"""
    devices = Device.get_all_devices()
    return success_response([device.to_dict() for device in devices])


@device_bp.route('/<int:device_id>', methods=['GET'])
@response_with_handler
def get_device(device_id):
    """获取单个设备"""
    device = Device.get_device_by_id(device_id)
    if device is None:
        return error_response("设备不存在", code=404)
    return success_response(device.to_dict())


@device_bp.route('/', methods=['POST'])
@response_with_handler
def create_device():
    """创建设备"""
    data = request.get_json()
    if not data or 'name' not in data:
        return error_response("缺少必要的参数: name", code=400)

    device = Device.create_device(data)
    return success_response(device.to_dict(), "设备创建成功")


@device_bp.route('/<int:device_id>', methods=['PUT'])
@response_with_handler
def update_device(device_id):
    """更新设备"""
    device = Device.get_device_by_id(device_id)
    if device is None:
        return error_response("设备不存在", code=404)

    data = request.get_json()
    updated_device = device.update_device(data)
    return success_response(updated_device.to_dict(), "设备更新成功")


@device_bp.route('/<int:device_id>', methods=['DELETE'])
@response_with_handler
def delete_device(device_id):
    """删除设备"""
    result = Device.delete_device(device_id)
    if not result:
        return error_response("设备不存在", code=404)
    return success_response(message="设备删除成功")